<template>
    {{ WardAreaForm }}
    <div class="container">
        <div class="left-section">
            <div v-if="officeTreeData.length === 0">加载中，请稍候...</div>
            <pre v-if="false">{{ JSON.stringify(officeTreeData, null, 2) }}</pre>
            <ElTree :data="officeTreeData" :props="departmentProps" @node-click="handleNodeClick" highlight-current
                default-expand-all v-loading="loading" element-loading-text="加载中..." />
            <div class="note">注: 自动从HIS获取科室区域数据</div>
            <div class="note">本页为病区分配病房，点击科室获取不到病房数据</div>
        </div>
        <div class="right-section">
            <h2 v-if="currentWardAreaName">当前病区: {{ currentWardAreaName }}</h2>
            <div class="ward-group" v-loading="loading">
                <div class="assigned-ward">
                    <h3>已分配病房</h3>
                    <template v-for="(ward, index) in assignedWards" :key="ward.wardId">
                        <ElCheckbox :id="ward.wardId" :label="ward.wardName" :checked="selectedWardIds.includes(ward.wardId)"
                            @change="handleWardChange(ward)" class="ward-checkbox" />
                        <!--:disabled="true"-->
                    </template>
                    <div v-if="assignedWards.length === 0" class="empty-message">暂无已分配病房</div>
                </div>
                <div class="unassigned-ward">
                    <h3>可分配病房</h3>
                    <template v-for="(ward, index) in unassignedWards" :key="ward.WardId">
                        <ElCheckbox :label="ward.wardName" :checked="selectedWardIds.includes(ward.wardId)"
                            @change="handleWardChange(ward)" class="ward-checkbox" />
                    </template>
                    <div v-if="unassignedWards.length === 0" class="empty-message">没有可分配的病房</div>
                </div>
            </div>
            <div class="button-group">
                <ElButton type="primary" @click="saveConfig()" :disabled="!selectedWardIds.length || loading"
                    :loading="loading">保存
                </ElButton>
                <ElButton @click="resetConfig" style="margin-left: 10px" :disabled="loading">重置</ElButton>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, computed } from 'vue';
import { ElTree, ElCheckbox, ElButton, ElMessage } from 'element-plus';
import { useRoute } from 'vue-router';
import http from '@/api/http.js';

// API Response Enums - 使用英文避免编码问题
enum APIEnum {
    QUERY_SUCCESS = 100,
    QUERY_FAIL = 101,
    CREATE_SUCCESS = 200,
    CREATE_FAIL = 201,
    UPDATE_SUCCESS = 300,
    UPDATE_FAIL = 301,
    DELETE_SUCCESS = 400,
    DELETE_FAIL = 401,
}

// TypeScript Interfaces
interface Ward {
    wardId: string;
    wardName: string;
    isAssigned: boolean;
}

interface TreeNode {
    id: string | number;
    label: string;
    children?: TreeNode[];
    [key: string]: any; // 允许其他字段
}

interface OfficeTreeNode {
    wardAreaId: string;
    iabel: string;
    children?: OfficeTreeNode[];
}

interface ApiResponse<T> {
    code: number;
    message?: string;
    data?: T;
}

const route = useRoute();

//#region // 科室+病区树形结构
const officeTreeData = ref<any[]>([]);
const departmentProps = ref({
    children: 'children',
    label: 'label',
    id: 'id'
});

// 当前选中的病区信息
const currentWardAreaId = ref(0);
const currentWardAreaName = ref('');

// 病房数据
const assignedWards = ref<Ward[]>([]);      // 已分配的病房
const unassignedWards = ref<Ward[]>([]);    // 未分配的病房
const selectedWardIds = ref<string[]>([]);  // 用户选择的病房ID
const loading = ref(false);                 // 加载状态

// 初始化数据
onMounted(() => {
    loadOfficeTreeData(); // 加载科室树形结构
});

// 获取科室树形数据
const loadOfficeTreeData = () => {
    loading.value = true;
    http.get('api/Management/OfficeHouseTree')
        .then((res) => {
            // console.log('科室数据:', res);
            if (res.code === 100) {
                const treeData = res.data || [];
                officeTreeData.value = treeData;
            } else {
                ElMessage.warning(`获取科室数据失败: ${res.message || '请稍后重试'}`);
            }
            loading.value = false;
        })
        .catch((error: Error) => {
            console.error('获取科室树形结构数据失败:', error);
            ElMessage.error('网络错误，请检查网络连接');
            loading.value = false;
        });
};

// 将后端返回的树形数据转换为组件需要的格式
function convertTreeData(data: TreeNode[]): OfficeTreeNode[] {
    if (!data || !Array.isArray(data)) {
        console.error('传入的数据不是数组:', data);
        return [];
    }

    return data.map(item => {
        // 创建一个包含所有原始属性的新对象
        const node: any = { ...item };

        // 确保WardAreaId存在
        node.WardAreaId = String(item.id || '');

        // 递归处理子节点
        if (item.children && Array.isArray(item.children)) {
            node.children = convertTreeData(item.children);
        }

        return node;
    });
}

// 点击树节点事件处理
const handleNodeClick = (data: any) => {
    if (!data.id) {
        ElMessage.warning('未获取到病区ID，请联系管理员');
        return;
    }

    console.log('点击树节点事件处理获取到的病区Id:', data.id);
    currentWardAreaId.value = data.id;
    currentWardAreaName.value = data.label;
    selectedWardIds.value = []; // 重置选择

    loadWardsByWardAreaId(data.id);
};
//#endregion

//#region // 病房数据
// const WardAreaForm = reactive({
//     wardAreaId: currentWardAreaId.value||0,
//     wardIds: selectedWardIds.value||0
// });

//#region // 病房数据
const zhi = ref('')
const WardAreaForm = computed(() => {
    const wardAreaIdValue = currentWardAreaId.value || 0;
    const wardIdsString = selectedWardIds.value.toString(); // 将数组转换为逗号分隔的字符串
    // 构造 application/x-www-form-urlencoded 格式的字符串
    zhi.value = `wardAreaId=${wardAreaIdValue}&wardIds=${wardIdsString}`;
    return zhi.value
});

const saveConfig = () => {
    // console.log('保存病房配置', WardAreaForm); // WardAreaForm 现在是 computed，需要访问 .value
    // http.post('api/Management/SaveWardServices?wardAreaId=' + WardAreaForm.wardAreaId + '&wardIds=' + WardAreaForm.wardIds.toString()) // 发送 computed 的值
    // alert('api/Management/SaveWardServices?' + zhi.value)
    http.post('api/Management/SaveWardServices?' + zhi.value).then((res) => {
        // 检查响应的状态码或结构
        if (res.code == 200) { // 假设成功代码是 200，请根据后端实际返回修改
            console.log('保存病房配置成功', res);
            ElMessage.success('保存成功'); // 显示成功消息
            // 清空已分配病房和未分配病房
            assignedWards.value = [];
            unassignedWards.value = [];
            selectedWardIds.value = [];
            // 重新加载病房数据
            loadWardsByWardAreaId(currentWardAreaId.value);
        } else {
            // 处理非成功响应，可能包含错误信息
            const errorMessage = res && res.message ? res.message : '保存配置失败，服务器返回非预期数据';
            assignedWards.value = [];
            unassignedWards.value = [];
            console.error('保存病房配置失败', res);
            ElMessage.error(errorMessage); // 显示错误消息
        }
    }).catch((error) => {
        // 处理网络错误或其他异常
        console.error('保存病房配置失败', error);
        ElMessage.error('保存配置时发生网络错误'); // 显示网络错误
    });
};

// 根据病区ID加载病房数据
const loadWardsByWardAreaId = (wardAreaId: number) => {
    // console.log('获取到的病区Id:', wardAreaId);
    // console.log('参数值:', wardAreaId) // 确认值是否正确
    // console.log('最终URL:', `api/Management/Ward?WardAreaId=${wardAreaId}`)
    loading.value = true;
    http.get('api/Management/WardAreaWardHouse?WardAreaId=' + wardAreaId)
        .then((res) => {
            console.log('获取到的病房数据:', res.data);
            if (res.code === 100) {
                const wards = res.data || [];
                assignedWards.value = wards.filter((ward: any) => ward.isAssigned);
                unassignedWards.value = wards.filter((ward: any) => !ward.isAssigned);
                selectedWardIds.value = assignedWards.value.map(ward => ward.wardId);
            } else {
                ElMessage.warning(`获取病区[${currentWardAreaName.value}]病房数据失败: ${res.data.message || '未知错误'}`);
            }
            loading.value = false;
        })
        .catch((error: Error) => {
            console.error(`获取病区[${currentWardAreaName.value}]病房数据失败`, error);
            ElMessage.error('加载病房数据时网络错误，请检查网络连接');
            loading.value = false;
        });
};

// 处理病房选择状态变化
const handleWardChange = (ward: Ward) => {
    const wardId = ward.wardId;

    if (selectedWardIds.value.includes(wardId)) {
        selectedWardIds.value = selectedWardIds.value.filter(id => id !== wardId);
    } else {
        selectedWardIds.value.push(wardId);
    }
};

const resetConfig = () => {
    console.log('重置病房配置');
    // 恢复初始勾选状态，先重新加载病房数据
    if (currentWardAreaId.value) {
        loadWardsByWardAreaId(currentWardAreaId.value);
    }
    selectedWardIds.value = [];
};
//#endregion
</script>

<style scoped>
.container {
    display: flex;
    max-width: 1200px;
    margin: 0 auto;
    font-family: 'Microsoft YaHei', sans-serif;
}

.left-section {
    width: 300px;
    border-right: 1px solid #e0e0e0;
    padding: 20px;
}

.right-section {
    padding: 20px;
    flex: 1;
}

.ward-group {
    margin-bottom: 20px;
}

.assigned-ward,
.unassigned-ward {
    margin-bottom: 30px;
}

.ward-checkbox {
    margin-right: 15px;
    margin-bottom: 10px;
}

.button-group {
    margin-top: 20px;
}

.note,
.assigned-note {
    font-size: 12px;
    color: #666;
    margin-top: 5px;
}

h3 {
    margin-bottom: 15px;
    color: #333;
    font-size: 16px;
}
</style>